package com.the_ring.chapter05;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import com.the_ring.chapter05.bean.UserInfo;
import com.the_ring.chapter05.database.UserHelper;

import java.lang.reflect.Type;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnFocusChangeListener {

    private static int PASSWORD_LOGIN = 0;
    private static int AUTH_CODE_LOGIN = 1;

    private int loginMode = 0;
    private String correctPwd = "123456";
    private String savePwd = "";

    RadioGroup loginModeRg;

    TextView passwordTv;
    EditText phoneEt, passwordEt;
    Button passwordBt;
    CheckBox rememberCb;
    Button loginBt;

    ActivityResultLauncher mLauncher;

    private UserHelper helper; // 数据库连接工具

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        helper = UserHelper.getInstance(this, 1);
        helper.openWriteLink();

        initView();

        mLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                Intent data = result.getData();
                String pwd = data.getStringExtra("pwd");
                correctPwd = pwd;

                // 保存密码到数据库
                helper.insert(new UserInfo(phoneEt.getText().toString(), pwd));
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        helper.closeLink();
    }


    private void initView() {
        loginModeRg = findViewById(R.id.rg_mode);
        passwordTv = findViewById(R.id.tv_pwd);
        phoneEt = findViewById(R.id.et_phone);
        passwordEt = findViewById(R.id.et_pwd);
        passwordBt = findViewById(R.id.bt_pwd);
        rememberCb = findViewById(R.id.cb_remember);
        loginBt = findViewById(R.id.bt_login);

        // 选择不同的登录方式显示不同
        loginModeRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                passwordEt.setText("");
                if (checkedId == R.id.rb_pwd) {
                    loginMode = PASSWORD_LOGIN;
                    passwordTv.setText("登录密码: ");
                    passwordEt.setHint("请输入密码");
                    passwordEt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    passwordBt.setText("忘记密码");
                    rememberCb.setVisibility(View.VISIBLE);

                    if (rememberCb.isChecked()) {
                        passwordEt.setText(savePwd);
                    }
                } else {
                    loginMode = AUTH_CODE_LOGIN;
                    passwordTv.setText("验证码: ");
                    passwordEt.setHint("请输入验证码");
                    passwordEt.setInputType(InputType.TYPE_CLASS_NUMBER);
                    passwordBt.setText("获取验证码");
                    rememberCb.setVisibility(View.GONE);
                }
            }
        });

        // 手机号11位
        phoneEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String phone = s.toString();
                if (phone.length() == 11) {
                    hideOneInputMethod(MainActivity.this, phoneEt);
                }
            }
        });

        // 密码输入时判断手机号是否合法
        passwordEt.setOnFocusChangeListener(this);

        passwordBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (loginMode == PASSWORD_LOGIN) {
                    // 找回密码
                    if (!phoneIsValid()) {
                        showPhoneNotValidToast();
                        return;
                    }
                    String phone = phoneEt.getText().toString();
                    Intent intent = new Intent(MainActivity.this, PwdActivity.class);
                    intent.putExtra("phone", phone);
                    mLauncher.launch(intent);
                } else if (loginMode == AUTH_CODE_LOGIN) {
                    // 获取验证码
                    if (!phoneIsValid()) {
                        showPhoneNotValidToast();
                        return;
                    }
                    String phone = phoneEt.getText().toString();
                    new AlertDialog.Builder(MainActivity.this)
                            .setTitle("请记住验证码")
                            .setMessage("手机号" + phone + "，本次登录验证码是151949，请输入验证码")
                            .setPositiveButton("好的", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            })
                            .create()
                            .show();
                }
            }
        });

        loginBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (loginMode == PASSWORD_LOGIN) {
                    if (rememberCb.isChecked()) {
                        savePwd = passwordEt.getText().toString();
                    }
//                    if (passwordEt.getText().toString().equals(correctPwd)) {

                    // 修改为数据库验证
                    if (validate(phoneEt.getText().toString(), passwordEt.getText().toString())) {

                        new AlertDialog.Builder(MainActivity.this)
                                .setTitle("登陆成功")
                                .setMessage("您的手机号码是" + phoneEt.getText().toString() + "，恭喜你通过登录验证，点击“确定”按钮返回上个页面")
                                .setNegativeButton("我再看看", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .setPositiveButton("确定返回", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        finish();
                                    }
                                })
                                .create()
                                .show();

                        // 登录成功时选中记录密码保存密码
                        if (rememberCb.isChecked()) {
                            UserInfo info = new UserInfo(phoneEt.getText().toString(),
                                    passwordEt.getText().toString());
                            helper.insert(info);
                        }

                    } else {
                        Toast.makeText(MainActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                    }
                } else if (loginMode == AUTH_CODE_LOGIN) {
                    if (passwordEt.getText().toString().equals("151949")) {
                        new AlertDialog.Builder(MainActivity.this)
                                .setTitle("登陆成功")
                                .setMessage("您的手机号码是" + phoneEt.getText().toString() + "，恭喜你通过登录验证，点击“确定”按钮返回上个页面")
                                .setNegativeButton("我再看看", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .setPositiveButton("确定返回", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        finish();
                                    }
                                })
                                .create()
                                .show();
                    } else {
                        Toast.makeText(MainActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

    }


    // 根据手机号查询指定记录
    public UserInfo queryByPhone(String phone) {
        UserInfo info = null;
        List<UserInfo> infoList = helper.query(String.format("phone='%s'", phone));
        if (infoList.size() > 0) {
            info = infoList.get(0);
        }
        return info;
    }

    public boolean validate(String phone, String pwd) {
        // 数据库是否有数据
        UserInfo info = queryByPhone(phone);
        if (info == null) {
            return pwd.equals("123456");
        } else {
            return pwd.equals(info.getPwd());
        }
    }



    private boolean phoneIsValid() {
        String phone = phoneEt.getText().toString();
        if (phone.length() != 11) return false;
        else if (!phone.startsWith("1")) return false;
        return true;
    }

    public static void hideOneInputMethod(Activity act, View v) {
        // 从系统服务中获取输入法管理器
        InputMethodManager imm = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE);
        // 关闭屏幕上的输入法键盘
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }

    public void showPhoneNotValidToast() {
        Toast.makeText(this, "请输入合法手机号！！", Toast.LENGTH_SHORT).show();
        phoneEt.requestFocus();
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (v.getId() == R.id.et_pwd && hasFocus) {
            if (!phoneIsValid()) {
                showPhoneNotValidToast();
                return;
            }

            // 保存密码的情况下，数据库查询密码自动填入密码
            if (rememberCb.isChecked()) {
                String phone = phoneEt.getText().toString();
                UserInfo info = queryByPhone(phone);
                if (info != null) {
                    passwordEt.setText(info.getPwd());
                }
            }
        }
    }
}